package cn.strongme.security.common.util;

import lombok.Data;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author Walter
 */
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 7446160142600110072L;

    public static final int NO_LOGIN = -1;

    public static final int SUCCESS = 0;

    public static final int FAIL = 1;

    public static final int NO_PERMISSION = 2;

    private String msg = "success";

    private int code = SUCCESS;

    private T data;

    public R() {
        super();
    }

    public Boolean success() {
        return (code == SUCCESS);
    }

    public Boolean getSuccess() {
        return success();
    }

    public static R builder() {
        return new R();
    }

    public R<T> code(int code) {
        this.code = code;
        return this;
    }

    public R<T> msg(String msg) {
        this.msg = msg;
        return this;
    }

    public R<T> data(T data) {
        this.data = data;
        return this;
    }

    public static <T> R<T> ok(String msg) {
        return builder().msg(msg);
    }

    public static <T> R<T> okData(String msg, T data) {
        return builder().msg(msg).data(data);
    }

    public static <T> R<T> okData(T data) {
        return okData("success", data);
    }

    public static <T> R<T> error(int code, String msg) {
        return builder().msg(msg).code(code);
    }

    public static <T> R<T> error(String msg) {
        return builder().msg(msg).code(FAIL);
    }

    public static <T> R<T> errorData(String msg, T data) {
        return builder().msg(msg).code(FAIL).data(data);
    }

    public static <T> R<T> errorData(T data) {
        return errorData("fail", data);
    }

    public static <T> R<T> error() {
        return error("fail");
    }

    public static <T> R<T> error(Throwable e) {
        return error(e.getMessage());
    }

}
